package cn.suxiaoxiang.suwebverify.api;



import cn.suxiaoxiang.suwebverify.SuWebVerify;

import cn.suxiaoxiang.suwebverify.config.MessageConfig;
import cn.suxiaoxiang.suwebverify.entity.DTO.loginDTO;
import cn.suxiaoxiang.suwebverify.util.EncryptionUtil;
import cn.suxiaoxiang.suwebverify.util.IsOnlinePlayer;
import cn.suxiaoxiang.suwebverify.util.PasswordUtil;
import cn.suxiaoxiang.suwebverify.util.SQLiteManager;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.potion.PotionEffectType;
import org.json.simple.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import static cn.suxiaoxiang.suwebverify.SuWebVerify.main;
import static cn.suxiaoxiang.suwebverify.events.PlayerJoin.PLAYER_SESSIONS;
import static sun.font.FontUtilities.getLogger;

import cn.suxiaoxiang.suwebverify.util.AutoLoginCache;

/**
 * Login - 玩家登录API
 *
 * @author 程序员-Su_xiaoxiang
 * @date 2025/4/7 11:43
 */
@WebServlet("/api/login")
public class Login extends HttpServlet {
    private final SuWebVerify thisplugin;
    private MessageConfig messageConfig;

    public Login(SuWebVerify plugin) {
        this.thisplugin = plugin;
        this.messageConfig = new MessageConfig(plugin);
        this.messageConfig.loadPlayerCommandConfig();  // 加载配置文件
    }
    //获取插件前缀
    String prefix = main.getConfig().getString("prefix");
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=UTF-8");
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");

        StringBuilder requestBody = new StringBuilder();
        try (BufferedReader reader = req.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }
        }

        // 使用 Gson 解析请求体中的 JSON 数据
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(requestBody.toString(), JsonObject.class);
        String encryptedData = jsonObject.get("encryptedData").getAsString();

        // 解密数据
        String decryptedData = EncryptionUtil.decrypt(encryptedData);
        if (decryptedData == null) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", false);
            responseJson.put("message", "数据解密失败！");
            resp.getWriter().write(responseJson.toJSONString());
            return;
        }

        // 解析解密后的数据
        loginDTO commandRequest = gson.fromJson(decryptedData, loginDTO.class);
        String username = commandRequest.getUsername();
        String password = commandRequest.getPassword();

        // 判断玩家是否在线
        if (!IsOnlinePlayer.isOnline(username)) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", false);
            responseJson.put("message", "玩家不在线，请确保玩家处于在线状态！");
            resp.getWriter().write(responseJson.toJSONString());
            return;
        }

        // 验证玩家密码
        if (!validatePlayerPassword(username, password)) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            JSONObject responseJson = new JSONObject();
            responseJson.put("success", false);
            responseJson.put("message", "密码错误，请重试！");
            resp.getWriter().write(responseJson.toJSONString());
            return;
        }

        PLAYER_SESSIONS.put(username, true);
        // 记录自动登录信息
        String ip = req.getRemoteAddr();
        AutoLoginCache.recordLogin(ip, username);
        //System.out.println("[SuWebVerify][AutoLogin] 登录API成功: 记录IP=" + ip + ", 玩家=" + username);
        Player player = Bukkit.getPlayer(username);
        if (player != null) {
            // 在调用 removePotionEffect 前，强制同步到主线程
            /*Bukkit.getScheduler().runTask(thisplugin, () -> {
                player.removePotionEffect(PotionEffectType.SPEED); // 示例操作
            });*/

            String loginSuccessful = messageConfig.getPlayerCommandConfig().getString("LoginSuccessful");
            player.sendMessage(prefix+loginSuccessful);
        }

        JSONObject responseJson = new JSONObject();
        responseJson.put("success", true);
        responseJson.put("message", "登录成功！");
        resp.getWriter().write(responseJson.toJSONString());
    }

    private boolean validatePlayerPassword(String username, String password) {
        String sql = "SELECT * FROM player WHERE username = ?";
        try (PreparedStatement pstmt = SQLiteManager.getConnection().prepareStatement(sql)) {
            pstmt.setString(1, username);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    String storedPassword = rs.getString("password");
                    return PasswordUtil.matches(password, storedPassword);
                }
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}
